package edu.chinasoft.servlet;

import edu.chinasoft.domain.User;
import edu.chinasoft.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;


@WebServlet(name="myUserLoginServlet",value="/servlet/userloginservlet")
public class UserLoginServlet extends HttpServlet {
	private static Logger logger = LoggerFactory.getLogger(UserLoginServlet.class);
	private UserService userService;
       
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info(" UserLoginServlet >doGet start.......");
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		//获取表单提交的数据
		String userName = request.getParameter("user_name");
		String userPassword = request.getParameter("user_password");
		//String verificationCodeClient = request.getParameter("user_code_verification");
		User user = new User();
		user.setUserName(userName);
		user.setUserPassword(userPassword);
		//获取spring框架的配置文件创建的服务层对象
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
		UserService userServiceImp = wac.getBean("userService",UserService.class);
		userService = userServiceImp;

		User userLoginInfo = userService.selectUserByNameAndPassword(user);
		if(userLoginInfo!=null){//用户存在
			//把登录信息保存在域里
			HttpSession session = request.getSession();
			session.setAttribute("userLogin",userLoginInfo);
			request.getRequestDispatcher("/main.jsp").forward(request,response);

		}else {//用户不存在
			request.getRequestDispatcher("/login_fail.jsp").forward(request,response);
		}

		logger.info(" UserLoginServlet >doGet end.......");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info(" UserLoginServlet >doPost start.......");
		this.doGet(request, response);

		logger.info(" UserLoginServlet >doPost end.......");
	}

}
